package com.springbootee.Common.aop;

import com.springbootee.Common.Rest;
import com.springbootee.Common.base.UserHolder;
import com.springbootee.Service.UserService;
import com.springbootee.entity.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.lang.Nullable;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.PrintWriter;
import java.util.logging.Logger;

@Component
public class UserInterceptor  implements HandlerInterceptor {
    @Autowired
    public UserService userService;
    @Override
 public  boolean preHandle(HttpServletRequest  request, HttpServletResponse response,Object obj) throws  Exception{
        //取出token
        String token=request.getHeader("token");
        User user=null;
        if (token != null){
            //根据token查出用户信息
       user =userService.getUserByToken(token);

        }
        //设置当前用户
        UserHolder.setUser(user);
        return true;
    }


        @Override
     public  void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, @Nullable Exception ex) throws Exception{
        //清除ThreadLocal中的信息，防止内存溢出
        UserHolder.remove();
}
/**
 *返回json数据
 * @param response
 * @param  r
 */
        private void returnJson(HttpServletResponse response, Rest r){
            PrintWriter writer=null;
            response.setCharacterEncoding("UTF-8");
            response.setContentType("application/json;charset=UTF-8");
            try{
                writer =response.getWriter();
                writer.print(com.alibaba.fastjson.JSON.toJSONString(r));
            }catch (Exception e){
                e.printStackTrace();
            }finally {
                    if (writer !=null){
                    writer.close();
                    }
            }
        }
}
